package com.wtwd.campus.utils.Vizhi.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.entity.LocationInfo;
import com.wtwd.campus.service.OrientationCacheService;
import com.wtwd.campus.utils.HttpclientUtil;
import com.wtwd.campus.utils.Vizhi.VizhiService;
import com.wtwd.campus.utils.Vizhi.entity.*;
import com.wtwd.campus.utils.Vizhi.entity.vo.VizhiGeocodingVo;
import com.wtwd.campus.utils.Vizhi.entity.vo.VizhiLocationVo;
import com.wtwd.campus.utils.Vizhi.entity.vo.VizhiVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VizhiServiceImpl implements VizhiService {

    private static final Logger logger = LoggerFactory.getLogger(VizhiServiceImpl.class);

    @Resource
    private OrientationCacheService orientationCacheService;

    @Override
    public VizhiVo intelligentHardwareLocation(String imei, List<Wifi> wifis, List<Cellular> cellulars) {
        VizhiData vizhiData = new VizhiData();
        vizhiData.setTimestamp(new Date().getTime());
        vizhiData.setId(UUID.randomUUID().toString());
        Asset asset = new Asset();
        asset.setId(imei);
        vizhiData.setAsset(asset);
        VizhiLocation vizhiLocation = new VizhiLocation();
        vizhiLocation.setWifis(wifis);
        vizhiLocation.setCellulars(cellulars);
        vizhiData.setLocation(vizhiLocation);
        String jsonString = JSONObject.toJSONString(vizhiData);
        JSONObject data = JSON.parseObject(jsonString);
        String url = URL.replace("{YOUR_ACCESS_KEY}", String.format("%s", ACCESS_KEY));
        logger.info("request 维智物联 智能硬件定位  data={}", data);
        VizhiVo vizhiVo = null;
        try {
            String locationJson = HttpclientUtil.httpPost(url, data);
            logger.info("response 维智物联 智能硬件定位 result={}", locationJson);
            vizhiVo = JSONObject.parseObject(locationJson, VizhiVo.class);
        } catch (Exception e) {
            logger.error("response 维智物联 智能硬件定位 定位异常 imei={} 异常信息={}", e.getMessage());
            throw new RuntimeException(e);
        }
        if (vizhiVo == null || vizhiVo.getLocation() == null || vizhiVo.getLocation().getPosition() == null || vizhiVo.getLocation().getPosition().getPoint() == null) {
            logger.error("response 维智物联 智能硬件定位 未得到定位信息 imei={}, data={}", imei, data);
            return null;
        }
        return vizhiVo;
    }

    @Override
    public VizhiVo intelligentHardwareLocation(String imei, String wifiInfo, String lbs) {
        List<Wifi> wifiList = new ArrayList<>();
        if (StringUtils.isNotBlank(wifiInfo)) {
            String[] wifis = wifiInfo.split("\\|");
            for (String wifi : wifis) {//单组wifi信息由mac和信号强度构成
                String[] split = wifi.split(",");
                String mac = split[0];
                String signalStrength = split[1];
                Wifi data = new Wifi();
                data.setMacAddress(mac);
                data.setSignalStrength(Integer.valueOf(signalStrength));
                wifiList.add(data);
            }
        }
        List<Cellular> cellulars = new ArrayList<>();
        if (StringUtils.isNotBlank(lbs)) {
            String[] lbsArray = lbs.split("\\|");
            long time = new Date().getTime();
            int mcc = 0;
            int mnc = 0;
            for (int i = 0; i < lbsArray.length; i++) {
                Cellular cellular = new Cellular();
                cellular.setTimestamp(time);
                cellular.setRadioType("gsm");
                if (i == 0) {//如果是第一组
                    String[] split = lbsArray[i].split(",");
                    mcc = Integer.parseInt(split[0]);
                    mnc = Integer.parseInt(split[1]);
                    int lac = Integer.parseInt(split[2]);
                    int cid = Integer.parseInt(split[3]);
                    int signalStrength = Integer.parseInt(split[4]);
                    cellular.setMobileCountryCode(mcc);
                    cellular.setMobileNetworkCode(mnc);
                    cellular.setCellId(cid);
                    cellular.setLocationAreaCode(lac);
                    cellular.setSignalStrength(signalStrength);
                } else {
                    String[] split = lbsArray[i].split(",");
                    int lac = Integer.parseInt(split[0]);
                    int cid = Integer.parseInt(split[1]);
                    int signalStrength = Integer.parseInt(split[2]);
                    cellular.setMobileCountryCode(mcc);
                    cellular.setMobileNetworkCode(mnc);
                    cellular.setCellId(cid);
                    cellular.setLocationAreaCode(lac);
                    cellular.setSignalStrength(signalStrength);
                }
                cellulars.add(cellular);
            }
        }
        VizhiVo vizhiVo = new VizhiVo();
        LocationInfo locationInfo = null;
        try {
            locationInfo = orientationCacheService.getCacheLocation(imei, wifiList, cellulars);
        } catch (Exception e) {
            logger.error("沃特定位缓存查询异常 imei={},wifiList={},cellulars={}, Exception={}", imei,wifiList.toString(),cellulars.toString(),e.getMessage());
        }
        if (locationInfo == null) {
            vizhiVo = intelligentHardwareLocation(imei, wifiList, cellulars);
            if (vizhiVo != null) {
                //to do 定位缓存
                try {
                    orientationCacheService.saveCacheLocation(cellulars, wifiList, imei, vizhiVo.getLocation().getPosition().getPoint().getLongitude(), vizhiVo.getLocation().getPosition().getPoint().getLatitude(),
                            VIZHI_DATA_SOURCE_TYPE, vizhiVo.getLocation().getPosition().getAccuracy(), vizhiVo.getLocation().getAddress().getName());
                } catch (Exception e) {
                    logger.error("沃特定位缓存存储异常 imei={},vizhiVo={} Exception={}", imei,vizhiVo.toString(),e.getMessage());
                }
            }
            return vizhiVo;
        }
        logger.info("命中沃特智能硬件定位缓存 result={}", locationInfo.toString());
        VizhiLocationVo vizhiLocationVo = new VizhiLocationVo();
        Address address = new Address();
        address.setName(locationInfo.getAddress());
        vizhiLocationVo.setAddress(address);
        Position position = new Position();
        Point point = new Point();
        point.setLatitude(locationInfo.getLat());
        point.setLongitude(locationInfo.getLng());
        position.setPoint(point);
        vizhiLocationVo.setPosition(position);
        vizhiVo.setLocation(vizhiLocationVo);
        return vizhiVo;
    }

    @Override
    public VizhiGeocodingVo InverseGeocoding(String getLng, String getLat) {
        VizhiGeocodingData vizhiGeocodingData = new VizhiGeocodingData();
        vizhiGeocodingData.setAsset(new Asset());
        LocationData locationData = new LocationData();
        Position position = new Position();
        Point point = new Point();
        point.setLongitude(Double.parseDouble(getLng));
        point.setLatitude(Double.parseDouble(getLat));
        position.setPoint(point);
        locationData.setPosition(position);
        vizhiGeocodingData.setLocation(locationData);
        String jsonString = JSONObject.toJSONString(vizhiGeocodingData);
        JSONObject data = JSON.parseObject(jsonString);
        String url = CODE_URL.replace("{YOUR_ACCESS_KEY}", String.format("%s", ACCESS_KEY));
        logger.info("request 维智物联 逆地理编码  data={}", data);
        VizhiGeocodingVo vizhiGeocodingVo1 = null;
        try {
            String locationJson = HttpclientUtil.httpPost(url, data);
            logger.info("response 维智物联 逆地理编码 result={}", locationJson);
            vizhiGeocodingVo1 = JSONObject.parseObject(locationJson, VizhiGeocodingVo.class);
        } catch (Exception e) {
            logger.error("response 维智物联 智能硬件定位 定位异常 imei={} 异常信息={}", e.getMessage());
            throw new RuntimeException(e);
        }
        return vizhiGeocodingVo1;
    }

    /**
     * 真那个硬件定位
     *
     * @param args
     */
    public static void main(String[] args) {
        String imei = "123456";
        String wifiInfo = "4e:77:66:49:18:8a,-37|00:4b:f3:a8:3e:9a,-89|02:4b:f3:a8:3e:9a,-89|e2:94:c7:7f:30:57,-90|ac:0b:fb:25:78:59,-92";
        List<Wifi> wifiList = new ArrayList<>();
        String[] wifis = wifiInfo.split("\\|");
        for (String wifi : wifis) {//单组wifi信息由mac和信号强度构成
            String[] split = wifi.split(",");
            String mac = split[0];
            String signalStrength = split[1];
            Wifi data = new Wifi();
            data.setMacAddress(mac);
            data.setSignalStrength(Integer.valueOf(signalStrength));
            wifiList.add(data);
        }
        VizhiData vizhiData = new VizhiData();
        vizhiData.setTimestamp(new Date().getTime());
        vizhiData.setId(UUID.randomUUID().toString());
        Asset asset = new Asset();
        asset.setId("123456");
        vizhiData.setAsset(asset);
        VizhiLocation vizhiLocation = new VizhiLocation();
        vizhiLocation.setWifis(wifiList);
        vizhiData.setLocation(vizhiLocation);
        String jsonString = JSONObject.toJSONString(vizhiData);
        JSONObject data = JSON.parseObject(jsonString);
        String url = URL.replace("{YOUR_ACCESS_KEY}", String.format("%s", ACCESS_KEY));
        logger.info("request 维智物联 智能硬件定位  data={}", data);
        String locationJson = HttpclientUtil.httpPost(url, data);
        logger.info("response 维智物联 智能硬件定位 result={}", locationJson);
        VizhiVo vizhiVo = JSONObject.parseObject(locationJson, VizhiVo.class);
        System.out.println(vizhiVo.toString());
    }

//    /**
//     * 逆地理编码
//     */
//    public static void main(String[] args) {
//        VizhiGeocodingData vizhiGeocodingData = new VizhiGeocodingData();
//        vizhiGeocodingData.setAsset(new Asset());
//        LocationData locationData = new LocationData();
//        Position position = new Position();
//        Point point = new Point();
//        point.setLongitude(Double.parseDouble("121.058657"));
//        point.setLatitude(Double.parseDouble("31.292376"));
//        position.setPoint(point);
//        locationData.setPosition(position);
//        vizhiGeocodingData.setLocation(locationData);
//        String jsonString = JSONObject.toJSONString(vizhiGeocodingData);
//        JSONObject data = JSON.parseObject(jsonString);
//        String url = CODE_URL.replace("{YOUR_ACCESS_KEY}", String.format("%s", ACCESS_KEY));
//        logger.info("request 维智物联 逆地理编码  data={}", data);
//        VizhiGeocodingVo vizhiGeocodingVo1 = null;
//        try {
//            String locationJson = HttpclientUtil.httpPost(url, data);
//            logger.info("response 维智物联 逆地理编码 result={}", locationJson);
//            vizhiGeocodingVo1 = JSONObject.parseObject(locationJson, VizhiGeocodingVo.class);
//        } catch (Exception e) {
//            logger.error("response 维智物联 智能硬件定位 定位异常 imei={} 异常信息={}", e.getMessage());
//            throw new RuntimeException(e);
//        }
//        System.out.println(vizhiGeocodingVo1.toString());
//    }
}
